﻿using EWS;
using Microsoft.Exchange.WebServices.Data;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XF.Meeting.Common;
using XF.Meeting.DAL;
using XF.Meeting.Entity.DTO;
using XF.Meeting.Entity.Query;

namespace QuartzJob.Jobs
{
    public class GetMeetFromExchange : IJob
    {
        ExchangeToDbDal dal = new ExchangeToDbDal();
        public  async System.Threading.Tasks.Task Execute(IJobExecutionContext context)
        {

            var service = ExChangeHelper.getExChangeHelper();
            var meetList = new List<Appointment>();
            //  ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            var meetss = service.GetRoomLists();
            foreach (var meetRooms in meetss)
            {
                var meetRoom = service.GetRooms(meetRooms);
                foreach (var room in meetRoom)
                {
                    try
                    {
                        var list = await  ExChangeHelper.GetEmailListByRoom(room.Address);
                     
                        //foreach (var meet in list)
                        //{
                        
                        //      await  InsertOrUpdate(meet);
                        //}
                    }
                    catch (Exception e)
                    {

                        continue;
                    }
                  

                }

            }
          
        }

        private Task<bool> InsertOrUpdate(XF.Meeting.Entity.DTO.EmailEntity meet)
        {

            bool check = dal.CheckIsCreated(meet);
            if (check)
            {
                return dal.Update(meet, out string ss);
            }
            else
            {
                meet.SourceType = 2;
                var (result, id) = dal.Insert(meet, out string ss).Result;
                double time = (meet.Start - DateTime.Now).TotalMinutes;
                bool isTen = false;
                isTen = time > 10 ? false : true;
                if (result)
                {
                    var wx = new WeChatHelper();
                    wx.SendWxMssage(new CRoomPadQuery()
                    {
                        CInfoId = id,
                        type = 1

                    }, isTen);
                }
                return System.Threading.Tasks.Task.FromResult(result);
            }
        }
        private bool InsertTemp(XF.Meeting.Entity.DTO.EmailEntity meet) {
            try
            {
                dal.InsertTemp(meet, out string s);
                if (s == "")
                {
                    return true;
                }
                else {
                    return false;
                }
            }
            catch (Exception e)
            {
                return false;
                throw;
            }
         
        }
    } }
